package com.xry.aspect;

import com.xry.annotation.LogMethod;
import com.xry.bean.Log;
import com.xry.mapper.LogDao;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class EasyAspect {

    @Autowired
    private LogDao logDao; // 注入LogDao

    @Around(value = "@annotation(logMethod)")
    public Object recordLog(ProceedingJoinPoint point, LogMethod logMethod) throws Throwable {
        Object result = null;
        // 获取注解属性
        String serviceName = logMethod.serviceName();
        boolean recordParam = logMethod.recordParam();
        boolean recordReturn = logMethod.recordReturn();

        // 获取方法信息
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        String methodName = methodSignature.getMethod().getName();

        // 构建日志对象
        Log log = new Log();
        log.setServicename(serviceName);
        log.setMethodname(methodName);
        log.setCreatetime(new Date()); // 设置当前时间

        // 处理参数
        if (recordParam) {
            Object[] args = point.getArgs();
            StringBuilder paramsBuilder = new StringBuilder();
            for (Object arg : args) {
                paramsBuilder.append(arg).append(", ");
            }
            if (paramsBuilder.length() > 0) {
                paramsBuilder.deleteCharAt(paramsBuilder.length() - 2); // 移除最后一个逗号和空格
            }
            log.setParams(paramsBuilder.toString());
        }

        // 执行目标方法
        try {
            result = point.proceed();
        } finally {
            // 处理返回值（无论是否异常都记录）
            if (recordReturn) {
                log.setReturnvalue(result != null ? result.toString() : "null");
            }

            // 保存日志到数据库
            logDao.add(log);
        }

        return result;
    }
}